package com.rq.app_base.use;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;


import com.base.rq.LOG;
import com.rq.app_base.CtrUI;

import java.lang.reflect.ParameterizedType;

import androidx.annotation.Nullable;

import static com.rq.app_base.use.BaseController.TAG_NAME;

/**
 * @author RQ
 * date    2021-07-07 15:24
 */
public class BaseActivity<P extends BaseController> extends Activity implements CtrUI<View> {

  BaseController mPresenter;

  @Override
  public View getView(int id) {
    return findViewById(id);
  }

  @Override
  public boolean openPage(Class clazz) {
    return false;
  }

  @Override
  public Context getContext() {
    return this;
  }

  @Override
  public void quit() {
    finish();
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    mPresenter = getController(this, 0);
    if (mPresenter == null) {
      Class<P> clazz = (Class<P>) getIntent().getSerializableExtra(TAG_NAME);
      LOG.e("BaseActivity", "onCreate.51:inner.pass" + clazz.getSimpleName());
      mPresenter = getController(clazz);
    }

    if (mPresenter != null) {
      setContentView(mPresenter.getLayoutId());
      mPresenter.setUi(this);
    }
    super.onCreate(savedInstanceState);
    if (mPresenter != null) {
      mPresenter.onViewCreated(savedInstanceState);
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    if (mPresenter != null) {
      mPresenter.onResume();
    }
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (mPresenter != null) {
      mPresenter.onPause();
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (mPresenter != null) {
      LOG.e("BaseActivity", "onActivityResult.259:");
      if (mPresenter.onActivityResult(requestCode, resultCode, data)) {
        return;
      }
    }
    super.onActivityResult(requestCode, resultCode, data);

  }

  /**
   * @param o
   * @param i
   *
   * @return
   */
  protected P getController(Object o, int i) {
    try {
      P back = getController((Class<P>) ((ParameterizedType) (o.getClass().getGenericSuperclass()))
          .getActualTypeArguments()[i]);
      //      back.setActivity(BaseActivity.this);
      return back;
    } catch (Exception e) {
      return null;
    }
  }

  public static <P extends BaseController> P getController(Class<P> clazz) {
    if (clazz == null) return null;
    try {
      return clazz.newInstance();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (ClassCastException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    }
    return null;
  }
}
